import { requestWithErrorHandling, instance } from "./request";

// 发送聊天消息
export function sendUserChatMessage(data) {
  return requestWithErrorHandling({
    url: "/user-chat/send",
    method: "POST",
    data: {
      senderId: data.senderId,
      receiverId: data.receiverId,
      content: data.content,
    },
    errorMessage: "发送消息失败",
  });
}

// 获取聊天历史记录
export function getChatHistory(data) {
  return requestWithErrorHandling({
    url: "/user-chat/history",
    method: "POST",
    data: {
      userId: data.userId,
      otherId: data.otherId,
      page: data.page || 1,
      size: data.size || 50,
    },
    errorMessage: "获取聊天历史失败",
  });
}

// 获取队列状态
export function getQueueStatus() {
  return requestWithErrorHandling({
    url: "/user-chat/queue",
    method: "GET",
    errorMessage: "获取队列状态失败",
  });
}

// 手动加入队列
export function joinQueue(data) {
  return requestWithErrorHandling({
    url: "/user-chat/join",
    method: "POST",
    data: {
      userId: data.userId,
      username: data.username,
    },
    errorMessage: "加入队列失败",
  });
}

// 手动离开队列
export function leaveQueue(data) {
  return requestWithErrorHandling({
    url: "/user-chat/leave",
    method: "POST",
    data: {
      userId: data.userId,
    },
    errorMessage: "离开队列失败",
  });
}

// WebSocket连接辅助函数
export function createChatWebSocket(
  userId,
  onMessage,
  onOpen,
  onClose,
  onError
) {
  // 获取token
  const token = localStorage.getItem("token");
  const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";

  // 优先尝试从 axios 实例中读取 baseURL，判断是否为本地后端
  const baseURL =
    (instance && instance.defaults && instance.defaults.baseURL) || "";
  const isLocalBackend = /localhost|127\.0\.0\.1/.test(baseURL);

  let wsUrl;
  if (isLocalBackend) {
    // 直接连接到后端的 WebSocket 地址（跳过 Vite 代理）
    // 例如 baseURL = "http://localhost:8080" -> hostPart = "localhost:8080"
    const hostPart = baseURL.replace(/^https?:\/\//, "").replace(/\/$/, "");
    wsUrl = `${wsProtocol}//${hostPart}/ws/chat?userId=${userId}&token=${encodeURIComponent(
      token || ""
    )}`;
    console.log("直接连接后端 WebSocket（未走 Vite 代理）");
  } else {
    // 使用 window.location.host 或相对地址，让 Vite 代理 /ws 转发到后端
    wsUrl = `${wsProtocol}//${
      window.location.host
    }/ws/chat?userId=${userId}&token=${encodeURIComponent(token || "")}`;
    console.log("使用 Vite 代理");
  }

  console.log("当前页面协议:", window.location.protocol);
  console.log("当前页面主机:", window.location.host);
  console.log("WebSocket URL:", wsUrl);

  try {
    const ws = new WebSocket(wsUrl);

    ws.onopen = (event) => {
      console.log("WebSocket连接已建立");
      onOpen && onOpen(event);
    };

    ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        onMessage && onMessage(message);
      } catch (error) {
        console.error("解析WebSocket消息失败:", error);
      }
    };

    ws.onclose = (event) => {
      console.log("WebSocket连接已关闭", {
        code: event.code,
        reason: event.reason,
        wasClean: event.wasClean,
      });
      onClose && onClose(event);
    };

    ws.onerror = (errorEvent) => {
      const stateMap = {
        0: "CONNECTING",
        1: "OPEN",
        2: "CLOSING",
        3: "CLOSED",
      };

      const info = {
        time: new Date().toISOString(),
        readyState: ws.readyState,
        readyStateName: stateMap[ws.readyState] || "UNKNOWN",
        url: ws.url,
        protocol: ws.protocol || "",
        online: typeof navigator !== "undefined" ? navigator.onLine : undefined,
        page: typeof window !== "undefined" ? window.location.href : undefined,
      };

      console.error("WebSocket 错误：", info, "原始事件：", errorEvent);

      // 如果事件中携带额外信息，打印出来以便排查
      try {
        if (errorEvent && errorEvent.message) {
          console.error("错误消息：", errorEvent.message);
        }
      } catch (e) {
        // 忽略二次错误
      }

      onError && onError(errorEvent);
    };

    return ws;
  } catch (error) {
    console.error("创建WebSocket失败:", error);
    onError && onError(error);
    return null;
  }
}

// 发送WebSocket消息
export function sendWebSocketMessage(ws, data) {
  console.log("sendWebSocketMessage调用:", {
    ws: !!ws,
    readyState: ws?.readyState,
    data,
  });

  if (ws && ws.readyState === WebSocket.OPEN) {
    const message = {
      type: "message",
      senderId: data.senderId,
      receiverId: data.receiverId,
      content: data.content,
      timestamp: new Date().toISOString(),
    };

    console.log("发送WebSocket消息:", message);
    ws.send(JSON.stringify(message));
    console.log("WebSocket消息已发送");
    return true;
  } else {
    console.log("WebSocket不可用:", {
      hasWs: !!ws,
      readyState: ws?.readyState,
      CONNECTING: WebSocket.CONNECTING,
      OPEN: WebSocket.OPEN,
      CLOSING: WebSocket.CLOSING,
      CLOSED: WebSocket.CLOSED,
    });
    return false;
  }
}

// 发送心跳消息
export function sendHeartbeat(ws) {
  if (ws && ws.readyState === WebSocket.OPEN) {
    const pingMessage = { type: "ping" };
    ws.send(JSON.stringify(pingMessage));
  }
}
